package com.sky.sd.system.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.sky.sd.common.web.response.Result;
import com.sky.sd.system.bean.dto.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * <br/>功能:
 * <br/>版本: 1.0
 * <br/>开发人员: 弓振
 * <br/>创建日期: 2020/7/1 15:55
 * <br/>修改日期: 2020/7/1 15:55
 * <br/>修改列表:
 */
public class LoginUserHolder {
    public static LoginUser getLoginUser(Authentication authentication) {
        LoginUser loginUser = new LoginUser();
        if(authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;
            Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
            if(userAuthentication instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken)userAuthentication;
                Object principal = usernamePasswordAuthenticationToken.getPrincipal();
                if(principal instanceof LoginUser) {
                    return (LoginUser) principal;
                }
                Map<String,Object> details = (Map<String, Object>) usernamePasswordAuthenticationToken.getDetails();
                Object principalMap = details.get("principal");
                return JSONObject.parseObject(JSONObject.toJSONString(principalMap), LoginUser.class);
            }
        }
        return null;
    }
}
